<template>
  <page-wrap  :loading="loading">
    <div class="certificate-container">
      <div class="tabs-list-box">
        <div class="list-item" v-for="(tab, index) in tabs" :key="index"
          :class="['tab-button', { active: activeTab === index }]" @click="setActiveTab(index)">
          {{ tab.label }}
        </div>
      </div>
      <div v-show="!scanning">
        <div class="certificate-header">请扫描或者输入券码核销</div>
        <div class="certificate-main" @click="scanner"></div>
      </div>
      <div v-show="scanning" class="container-new">
        <video id="video"></video>
        <div v-if="mask" class="mask"></div>
      </div>
      <div class="roomName">房台号：{{ route.query.roomName }}</div>

      <!-- @click="stop" -->
      <div class="certificate-footer">
        <input type="text" placeholder="请输入优惠券券码" class="certificate-footer-input" id="inputId" />
        <z-button @click="onSubmit"
          style="font-size: 16px;font-family: PingFang SC;font-weight: 500;margin: 5px;line-height: 16px;color: #260c04;border-radius: 3px;white-space: pre;">
          确认券码
        </z-button>
      </div>
      <div class="change-type" @click="changType">切换成兼容模式</div>
    </div>
    <z-dialog v-model:show="confirmSignshow" content="是否确认使用？" @confirm="onConfirmSign"></z-dialog>
  </page-wrap>
  <!-- 套餐弹窗 -->
  <ComboSelect v-model:show="comboSelectShow" :data="comboData" :isBanAddAll="true" @join="onJoinCombo"></ComboSelect>
  <z-popup v-model:show="comSelectShow" title="套餐选择">
    <div class="popup-block" style="min-width: 300px">
      <div class="popup-block-main">
        <div class="main-item" :class="comSelectActive == k ? 'select' : ''" v-for="(v, k) in comSelectList" :key="k"
          @click="selectCom(k)">
          {{ v.goodsName }}
        </div>
      </div>
      <div class="popup-block-footer">
        <z-button-group class="button-group">
          <z-button @click="comSelectShow = false" plain style="margin-right: 12px">取消</z-button>
          <z-button @click="comSelectComfirm">确定</z-button>
        </z-button-group>
      </div>
    </div>
  </z-popup>
</template>

<script setup>
import useConfigStore from '@/store/config'
import { calculateOrderQty } from '@/lib/util.js'
import { ZButton } from "@/components/Button";
// import { Html5Qrcode } from "html5-qrcode";
import { showToast } from "vant";
import Api from "@/api";
import { onMounted, ref , onUnmounted } from "vue";
import { BrowserMultiFormatReader } from '@zxing/library';
import _ from 'lodash'
const defutImage = ref('https://oss.jtmckj.com/wmp/qnjg/signin/defutImage.png')
const scanning = ref(false);
const cameraId = ref("");
const devicesInfo = ref("");
// const html5QrCode = ref(null);
const configStore = useConfigStore()

import ls from '@/lib/ls'
// const result = ref('')

let message = ref('');
let codeReader = null;
let selectedDeviceId = '';
let mask = ref(false);
function init() {
  // 识别和处理多种常见的条形码和二维码格式
  codeReader = new BrowserMultiFormatReader();
  // 获取当前设备上可用的视频输入设备列表
  codeReader.getVideoInputDevices().then(videoInputDevices => {
    if (videoInputDevices.length > 1) {
      // 后缀摄像头（手机）
      selectedDeviceId = videoInputDevices[1].deviceId;
    } else {
      // 前置摄像头
      selectedDeviceId = videoInputDevices[0].deviceId;
    }
  })
}

onMounted(() => {
  codeReader = null
  selectedDeviceId = ''
  message.value = '';
  init();
});

onUnmounted(() => {
  selectedDeviceId = ''
  codeReader = null
});

// 切换方式
const changType = ()=>{
  router.replace({path:'certificateSpe', query: { ...route.query }})
 
}

function scanner() {
  scanning.value = true
  mask.value = true
  // 自动打开指定的视频输入设备，并实时对视频流中的每一帧图像进行条形码和二维码的解码操作，此方法不是只进行一次解码尝试，而是在视频流持续传输的过程中，不断地对每一帧图像进行解码分析
  codeReader.decodeFromVideoDevice(selectedDeviceId, 'video', (result, err) => {
    if (result) {
      message.value = result.text;
      if (message.value ) {
        let inputElement = document.getElementById("inputId");
        inputElement.value = message.value;
        close()
        onSubmit();
      }
    }
    if (err) {
      // scanning.value = false
      // message.value = '摄像头访问被拒绝或发生错误1: ' + err.message;
      // let inputElement = document.getElementById("inputId");
      // inputElement.value = message.value;
      // mask.value = false;
      // codeReader.reset();
    }
  })

}
function close() {
  if(codeReader){
    codeReader.reset();
  }
  message.value = '';
  scanning.value = false
  mask.value = false;
}


onUnmounted(() => {
  close();
});


const router = useRouter();
const route = useRoute();
console.log(configStore.goodsList);
const confirmSignshow = ref(false);
const codeval = ref("");

const comSelectShow = ref(false) // 套餐选择弹窗
const comSelectList = ref([]) // 套餐选择数组
const comSelectActive = ref(0) // 选中的套餐

const onSubmit = () => {
  let inputValue = document.getElementById("inputId").value;
  codeval.value = document.getElementById("inputId").value;
  if (!inputValue) return;
  console.log("inputValue :>> ", inputValue);
  // router.push({
  //   path: '/open/certificate/ticketInfo',
  //   query: {
  //     code: inputValue,
  //     consumeCode: route.query.consumeCode,
  //     activeType:activeTab.value
  //   }
  // })

  if (activeTab.value == 1) { // 抖音券
    Api.Common.AppObjProcess.Do({
      functionName: "WriteOffTicketInfo",
      contentData: { tiktopCode: inputValue },
    })
      .then(res => {
        console.log(res);

        // const result = configStore.goodsList
        // .filter(goods => goods.type == '2' && goods.goodsCode === res.GoodsCode); // 过滤符合条件的商品

        const result = configStore.goodsList.filter(goods =>
          goods.type === '2' &&
          res.list.some(item => item.GoodsCode === goods.goodsCode)
        );

        console.log(result); // 输出符合条件的商品数组
        if (result && result.length == 1) {
          comSelectList.value = result
          resetCom(result[0]) // 处理套餐 
        } else if (result && result.length > 1) {
          comSelectList.value = result
          comSelectShow.value = true
        } else {
          showToast("暂无商品");
        }



      })
  }


  if (activeTab.value == 0) { // 兑换券
    getTicketInfo();
  }

  if (activeTab.value == 2) { // 美团券
    Api.Common.AppObjProcess.Do({
      functionName: "MtWriteOffTicketInfo",
      contentData: { receiptCode: inputValue },
    })
      .then(res => {
        console.log(res);
        // const result = configStore.goodsList
        // .filter(goods => goods.type == '2' && goods.goodsCode === res.GoodsCode); // 过滤符合条件的商品

        const result = configStore.goodsList.filter(goods =>
          goods.type === '2' &&
          res.list.some(item => item.GoodsCode === goods.goodsCode)
        );

        console.log(result); // 输出符合条件的商品数组
        if (result && result.length == 1) {
          comSelectList.value = result
          resetCom(result[0]) // 处理套餐 
        } else if (result && result.length > 1) {
          comSelectList.value = result
          comSelectShow.value = true
        } else {
          showToast("暂无商品");
        }



      })
  }
};

const selectCom = (e) => { // 选中套餐
  comSelectActive.value = e
}
const comSelectComfirm = () => { // 选中套餐确认
  const res = comSelectList.value[comSelectActive.value]
  console.log(res);

  resetCom(res)
}


const comboSelectShow = ref(false) // 套餐弹窗
const ticketInfo = ref({});
const getTicketInfo = (params) => {
  const data = {
    memberTicketCode: codeval.value,
  };
  Api.Common.AppObjProcess.Do({
    functionName: "GetGoodsTicket",
    contentData: data,
  })
    .then((res) => {

      console.log("获取券信息 res :>> ", res);
      ticketInfo.value = res;
      let obj = {
        list: [res]
      }
      console.log(configStore.goodsList);
      const result = configStore.goodsList.filter(goods =>
        obj.list.some(item => item.goodsCode === goods.goodsCode)
      );

      console.log(result); // 输出符合条件的商品数组
      if (result && result.length == 1) {
        if (result[0].type == '1') {
          confirmSignshow.value = true;
        } else {
          comSelectList.value = result
          resetCom(result[0]) // 处理套餐 
        }

      } else if (result && result.length > 1) {
        comSelectList.value = result
        comSelectShow.value = true
      } else {
        showToast("暂无商品");
      }
      // showToast('核销中，请稍等')
      // onConfirmSign()
    })
    .catch(() => { });
};

const comFlag = ref(false)
const loading = ref(false)
//二次确认
const onConfirmSign = () => {
  // if (comFlag.value) {
  //   showToast("加载中");
  //   return
  // }
  loading.value = true
  // 抖音核销卷
  if (activeTab.value == 1) {
    const data = {
      tiktopCode: codeval.value,
      consumeCode: route.query.consumeCode,
      detail: comDetail.value,
      roomCode: route.query.roomCode,
    };
    Api.Common.AppObjProcess.Do({
      functionName: "WriteOffTicket",
      contentData: data,
    })
      .then((res) => {
        confirmSignshow.value = false
        console.log("使用券 res :>> ", res);
        showToast("使用成功");
        setTimeout(() => {
          loading.value = false
          router.push({
            path: "/open",
          });
        }, 2000);
      })
      .catch(() => {
        loading.value = false
      });
  } else if (activeTab.value == 0) {
    const data = {
      memberTicketCode: codeval.value,
      consumeCode: route.query.consumeCode,
      memberCarCode: ticketInfo.value.memberCarCode,
      detail: comDetail.value,
      roomCode: route.query.roomCode,
    };
    Api.Common.AppObjProcess.Do({
      functionName: "UseGoodsTicket",
      contentData: data,
    })
      .then((res) => {
        confirmSignshow.value = false

        console.log("使用券 res :>> ", res);
        showToast("使用成功");
        setTimeout(() => {
          loading.value = false
          router.push({
            path: "/open",
          });
        }, 2000);

      })
      .catch(() => {
        loading.value = false
      });
  } else if (activeTab.value == 2) { // 美团券
    const data = {
      receiptCode: codeval.value,
      consumeCode: route.query.consumeCode,
      detail: comDetail.value,
      roomCode: route.query.roomCode,
    };
    Api.Common.AppObjProcess.Do({
      functionName: "MtWriteOffTicket",
      contentData: data,
    })
      .then((res) => {
        confirmSignshow.value = false

        console.log("使用券 res :>> ", res);

        showToast("使用成功");
        setTimeout(() => {
          loading.value = false
          router.push({
            path: "/open",
          });
        }, 2000);
      })
      .catch(() => {
        loading.value = false
      });
  }
};

// 定义 Tab 数据
const tabs = [{ label: "兑换卷" }, { label: "抖音卷" }, { label: "美团券" }];

// 设置当前选中的 Tab 索引
const activeTab = ref(0);

// 设置激活的 Tab
const setActiveTab = (index) => {
  activeTab.value = index;
};

const comboData = ref('')
const resetCom = (dyDetail) => {
  comSelectShow.value = false
  const detail = dyDetail.priceList[0].detail
  console.log(detail);
  for (let i = 0; i < detail.length; i++) {
    const goodsDetail = detail[i].goodsDetail;
    detail[i].allNum = 0
    for (let j = 0; j < goodsDetail.length; j++) {
      const flavor = goodsDetail[j];
      flavor.isShowFlavor = true // 是否显示规格
      flavor.flavor = '' // 已选规格
      flavor.canPlus = false // 步进器是否可加
      flavor.stepNum = flavor.defaultQty // 步进器数量
      flavor.percentPrice = 0
      flavor.vipPercentPrice = 0
      flavor.isSelect = false // 是否选中
      flavor.choiceType = detail[i].choiceType
      flavor.operType = detail[i].operType
      // flavor.stepNum = '' 
      // console.log(flavor.goodsFlavor);
      if (flavor.goodsFlavor) {
        if (flavor.goodsFlavor.includes('[')) {
          flavor.goodsFlavor = JSON.parse(flavor.goodsFlavor)
        }
        for (let item of flavor.goodsFlavor) {
          item.active = false
          if (typeof item.FlavorStr == 'string') {

            const str = item.FlavorStr;

            // 替换中文逗号为英文逗号
            const normalizedStr = str.replace(/[，,]/g, ',');
            // 使用英文逗号分隔字符串
            const parts = normalizedStr.split(',');
            // 将每个部分转换为对象
            const result = parts.map(part => {
              // 默认值
              let uomName = part.trim();
              let addprice = 0;
              let select = false;
              // 检查是否有#，设置select
              if (uomName.includes('#')) {
                select = true;
                uomName = uomName.replace('#', '').trim();
              }
              // 检查是否有*，设置addprice
              const match = uomName.match(/\*(\d+)$/);
              if (match) {
                addprice = parseInt(match[1], 10);
                uomName = uomName.replace(match[0], '').trim();
              }
              return { uomName, addprice, select };
            });
            console.log(result);

            item.sizeList = result

          }
        }
        console.log(flavor.goodsFlavor);

      }

    }
  }
  comboData.value = dyDetail
  comboSelectShow.value = true
}
const comDetail = ref('') // 处理过的套餐

const onJoinCombo = (product) => { // 套餐加入
  console.log(product);
  const arr = _.cloneDeep([product])
  if (arr.length <= 0) {
    showToast('购物车为空')
    return
  }
  const newArr = []
  arr.forEach((obj) => {
    if (obj.hasOwnProperty('detail')) {
      obj.detail.forEach((detail) => {
        const newDetail = { ...detail, type: '3' };
        newArr.push(newDetail);
      });
      delete obj.detail;
    }
    newArr.push(obj);
  });
  newArr.reverse()
  comDetail.value = newArr.map((obj, k) => {
    const { num, defaultQty, type, flavor, goodsPriceCode, stepNum, choiceType, isSelect, operType } = obj
    const convertedObj = {
      ...obj,
    };
    convertedObj.itemCode = ''
    convertedObj.doType = 'add'

    if (flavor == undefined) {
      convertedObj.flavor = ''
    }
    if (goodsPriceCode == undefined) {
      convertedObj.goodsPriceCode = ''
    }
    if (num !== undefined) {
      convertedObj.orderQty = num;
      delete convertedObj.num;
    }
    if (defaultQty !== undefined) {
      convertedObj.orderQty = defaultQty;
      delete convertedObj.defaultQty;
    }
    if (stepNum !== undefined) {
      convertedObj.orderQty = stepNum;
      delete convertedObj.stepNum;
    }
    if (choiceType == '1' && isSelect == false && operType == '0') { // choiceType == '1' 是挑选种类  isSelect false 未选中 operType == '1'固定项目 不能修改配置
      convertedObj.orderQty = 0
      delete convertedObj.choiceType;
      delete convertedObj.isSelect;
    }
    if (type == '0' || type == '1') {
      convertedObj.itemType = '1'
    }
    if (type === '2') {
      convertedObj.flavor = ''
      convertedObj.itemType = '2'
      convertedObj.goodsPriceCode = convertedObj.goodsCode;
    }
    if (type === '3') {
      convertedObj.itemType = '3'
      convertedObj.goodsPriceCode = convertedObj.packageCode;
      delete convertedObj.packageCode;
    }

    delete convertedObj.mathType;
    delete convertedObj.type;
    delete convertedObj.attachment;
    delete convertedObj.orgCode;
    delete convertedObj.goodsFlavor;
    delete convertedObj.isEstmClear;
    delete convertedObj.mainAttachment;

    return convertedObj;
  });
  // postForm.payType = '1'
  calculateOrderQty(comDetail.value)
  console.log(comDetail.value);
  confirmSignshow.value = true
  // return
  // postForm.totalAmt = postForm.detail.reduce((sum, item) => sum + Number(item.salePrice), 0)
}



</script>

<style scoped lang="scss">
.certificate-container {
  .certificate-header {
    padding: 29px 0px 50px 0px;
    text-align: center;
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #cccccc;
    line-height: 16px;
  }

  .certificate-main {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    background-image: url("@/assets/images/open/i_certificate_qrcode.png");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
  }

  .certificate-footer {
    margin-top: 100px;
    text-align: center;
    margin: 50px 38px 0 38px;
    background: #665f52;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .certificate-footer-input {
      width: 190px;
      background: #665f52;
      border-radius: 4px;
      padding-left: 15px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffaa00;
      line-height: 16px;
    }

    .certificate-footer-input::placeholder {
      color: #807766;
    }
  }
  .change-type{
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 13px;
    color: #FFFFFF;
    line-height: 13px;
    padding-top: 40px;
    padding-right: 10px;
    text-align: right;
  }
}

.tabs-list-box {
  margin-top: 10px;
  padding-left: 20px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;

  .list-item {
    margin-right: 20px;
    // width: 150px; 
    flex-basis: 25%;
    height: 40px;
    font-size: 16px;
    border-radius: 10px;
    line-height: 40px;
    text-align: center;
    color: #fff;
    background-color: #3d3d4c;
  }

  .active {
    background-color: #ffaa00;
    color: #fff !important;
  }
}

.popup-block {
  .popup-block-main {
    padding: 20px 24px 10px 24px;
    max-height: 300px;
    overflow-y: auto;
    .main-item {
      // height: 40px;
      background: #404047;
      border-radius: 8px;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: #FFFFFF;
      line-height: 40px;
      padding-left: 12px;
      margin-bottom: 10px;
      // white-space: nowrap;        /* 不换行 */
      // overflow: hidden;           /* 隐藏超出部分 */
      // text-overflow: ellipsis;    /* 超出部分用省略号表示 */
      &.select {
        border: 1px solid #FFDD99;
      }
    }
  }

  .popup-block-footer {
    padding: 10px 24px 20px 24px;

    .button-group {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.roomName {
  font-size: 32px;
  text-align: center;
  color: #ffffff;
  padding-top: 30px;
}

.container-new {
  margin-left: calc(50% - 100px);
  margin-top: 50px;
  width: 200px;
  height: 200px;
}

.container-new>video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

// .mask {
//   position: absolute;
//   left: 15%;
//   top: 20%; 
//   width: 100%;
//   height: 300px;
//   border-radius: 2px;
//   outline: rgba(0, 0, 0, .25) solid 20vmax;
// }</style>
